﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DcsGauges.Shared.Exceptions;

namespace DcsGauges.Shared.Network
{
    public class StringBuffer
    {
        #region Constants & Readonly
        
        public const int DEFAULT_BUFFER_SIZE                = 65535;
        private const float RESIZE_FACTOR                   = 1.5f;
        private static readonly Encoding encoding           = Encoding.UTF8;

        #endregion


        #region Fields & Properties

        public string ContentString     { get { return this.sb.ToString(); } }
        public static Encoding UsedEncoding
        {
            get { return encoding; }
        }

        private StringBuilder sb    = new StringBuilder();
        private int count           = 0;
        private int capacity        = DEFAULT_BUFFER_SIZE;

        #endregion


        #region Constructors

        public StringBuffer(int capacity)
        {
            if (capacity <= 0)
            {
                throw new DcsArgumentException(Localization.ExcStringBufferSizeAtLeastOne);
            }
        }

        public StringBuffer() : this(DEFAULT_BUFFER_SIZE)
        {

        }

        #endregion


        #region Operations

        public void Append(byte[] rawBuffer, int bytesRead)
        {
            string toAppend         = encoding.GetString(rawBuffer, 0, bytesRead);
            this.sb.Append(toAppend);
        }

        public void Remove(int length)
        {
            if(this.sb.Length < length)
                throw new DcsInvalidOperationException(string.Format(Localization.ExcReadingBufferRemove2A, length, this.sb.Length));
            this.sb.Remove(0, length);
        }

        public void Clear()
        {
            this.sb.Clear();
        }

        #endregion
    }
}
